import React, { useEffect, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { ArrowLeft, Ellipsis } from '@react-vant/icons';
import TopTitleBar from "../../components/TopTitleBar";
import { Form, Button, Input, Area, Field, Switch, Toast, Dialog } from 'react-vant';
import { areaList } from '@vant/area-data'
import "./index.css"
import axios from "../../utils/axios";
import { data } from "browserslist";
const AddressEdit = () => {
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const {
        state: {
            addressId: addressId,
            type
        }
    } = useLocation();
    const [areaVal, setAreaVal] = useState({})
    const areaDetailTitle = ['provinceName', 'cityName', 'regionName'];
    const onFinish = (val, option) => {
        if (type === 'add') {
            addAddressFun(val)
        }
        if (type === 'edit') {
            editAddressFun(val)
        }
    }
    // addressInfo :  (3) ['150000', '150400', '150402'] 翻转函数
    const addAddressFun = (val) => {
        axios.post('/api/v1/address', data = {
            cityName: areaVal.cityName,
            defaultFlag: val.defaultFlag,
            detailAddress: val.detailAddress,
            provinceName: areaVal.provinceName,
            regionName: areaVal.regionName,
            userName: val.userName,
            userPhone: val.userPhone
        }).then(res => {
            if (res.data.message === 'SUCCESS') {
                Toast.success('新增地址成功');
                navigate('/addressManagement', {
                    replace: true
                })
            }
        })
    }
    const editAddressFun = (val) => {
        axios.put('/api/v1/address', data = {
            addressId,
            cityName: areaVal.cityName,
            defaultFlag: val.defaultFlag,
            detailAddress: val.detailAddress,
            provinceName: areaVal.provinceName,
            regionName: areaVal.regionName,
            userName: val.userName,
            userPhone: val.userPhone
        }).then(res => {
            if (res.data.message === 'SUCCESS') {
                Toast.success('修改成功');
                navigate('/addressManagement', {
                    replace: true
                })
            }
        })
    }
    const onConfirmArea = (val, option) => {
        const tempObj = {}
        areaDetailTitle.map((b, i) => {
            tempObj[b] = option[i]?.text
        })
        setAreaVal(tempObj)
    }

    const getAddressDetails = () => {
        if (addressId) {
            axios.get(`/api/v1/address/${addressId}`).then(res => {
                if (res.data.message === 'SUCCESS') {
                    form.setFieldsValue(res.data.data);
                    // form.setFieldValue('addressInfo', res.data.data.provinceName)
                    setAreaVal(res.data.data)

                }
            }).catch(err => {
            })
        }
    }

    const handleDelete = () => {
        // 确定删除以后：
        axios.delete(`/api/v1/address/${addressId}`).then(res => {
            if (res.data.message === 'SUCCESS') {
                // 删除成功： 弹窗， 
                Toast.success('删除成功！')
                // 调回 上一页！
                navigate('/addressManagement', {
                    replace: true
                })
            }
        })
    }

    const clickDeleteBtn = () => {
        // 这个是 调起弹窗！
        Dialog.show({
            title: '确定要删除吗？',
            showCancelButton: true,
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            confirmButtonColor: 'red',
            onConfirm: handleDelete
        })
    }

    useEffect(() => {
        // form 的初始值呀
        // axis 获取 收货地址详情：或者 为 空：
        getAddressDetails();
    }, [])



    const tempObj = {}

    return (
        <div
            className="addressEdit"
        >
            <Form
                form={form}
                onFinish={onFinish}
                footer={
                    <div style={{ margin: '16px 16px 0' }}>
                        <Button
                            color="#1baeae"
                            round
                            nativeType='submit'
                            type='primary'
                            block
                        >
                            保存
                        </Button>
                    </div>
                }
            >
                <TopTitleBar
                    leftIcon={
                        <ArrowLeft onClick={() => navigate(-1)} />
                    }
                    intermediateContentText="新增地址"
                    rightIcon={
                        <Ellipsis />
                    }
                />
                <Form.Item
                    name='userName'
                    rules={[{ required: true, message: '请填写姓名' }]}
                    label='姓名'
                >
                    <Input placeholder="请输入用户名" />
                </Form.Item>
                <Form.Item
                    name='userPhone'
                    label='电话'
                    rules={[{
                        required: true,
                        message: '请输入正确的手机号',
                        pattern: /^1[3,4,5,6,7,8,9][0-9]{9}$/
                    }]}
                >
                    <Input placeholder="收货人手机号" />
                </Form.Item>
                <Form.Item
                    name='addressInfo'
                    label='地区'
                    className="addressInfo"
                >
                    <Area
                        popup
                        value={areaVal}
                        areaList={areaList}
                        onConfirm={onConfirmArea}
                    >
                        {/* 中间的 children是用来干嘛的 */}
                        {
                            (_, selectRows, actions) => {
                                return (
                                    <Field
                                        placeholder="选择省/市/区"
                                        value={
                                            type === 'edit' ? (areaVal.provinceName ? (areaVal.provinceName + '/' + areaVal.cityName + '/' + areaVal.regionName) : '') :
                                                selectRows.map(row => row?.text).join('/')}
                                        onClick={() => actions.open()}
                                    />
                                )
                            }
                        }
                    </Area>
                </Form.Item>
                <Form.Item
                    name='detailAddress'
                    label='详细地址'
                >
                    <Input placeholder="街道门牌、楼层房间号等信息" />
                </Form.Item>
                <Form.Item
                    name='defaultFlag'
                    label='设置为默认地址'
                    valuePropName="checked"
                >
                    {/* 切换 0 或者 1 */}
                    {/* 1：默认  0：非默认 */}
                    <Switch
                        size={20}
                        activeColor='#1baeae'
                        activeValue={1}
                        inactiveValue={0}
                    />

                </Form.Item>
            </Form>
            {
                type === 'edit' &&
                <div style={{ margin: '16px 16px 0' }}>
                    <Button
                        className="deleteBtn"
                        round
                        nativeType='submit'
                        type='primary'
                        block
                        onClick={clickDeleteBtn}
                    >
                        删除
                    </Button>
                </div>
            }
        </div>
    )
}

export default AddressEdit;